package top.wshape1.easyscan.activity;

import android.Manifest;
import android.app.Dialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.NavigationUI;

import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.bottomsheet.BottomSheetDialog;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collector;
import java.util.stream.Collectors;

import top.wshape1.easyscan.R;
import top.wshape1.easyscan.constraint.PackageEnum;
import top.wshape1.easyscan.custom.ApplicationJumpDialog;
import top.wshape1.easyscan.data.SettingData;
import top.wshape1.easyscan.databinding.ActivityEasyScanBinding;

public class EasyScanActivity extends AppCompatActivity {

    private static final String TAG = "EasyScanActivity";

    private BottomNavigationView navView;

    private ActivityEasyScanBinding binding;

    /**
     * All App‘s info
     */
    public Map<String, ApplicationInfo> goalAppInfoMap;

    public List<ApplicationInfo> applicationInfoList;

    private ClipboardManager clipboardManager;

    public ActivityResultLauncher<Intent> resultLauncher;

    public ApplicationJumpDialog jumpDialog;

    /**
     * 应用数据
     */
    public SettingData settingData;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityEasyScanBinding.inflate(getLayoutInflater());

        // 设置UI样式
        View decor = getWindow().getDecorView();
        decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        getWindow().setStatusBarColor(Color.TRANSPARENT);
        setContentView(binding.getRoot());

        // 请求权限
        requestPermission();

        // 获取View
        navView = binding.navView;

        // 设置底部导航栏
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_activity_easy_scan);
        NavigationUI.setupWithNavController(binding.navView, navController);

        // 获取支持的应用详细
        goalAppInfoMap = initGoalAppInfoMap();

        // 获取剪切板服务
        clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);

        // 初始化Scan跳转框
        jumpDialog = new ApplicationJumpDialog(this);
        jumpDialog.show();
        jumpDialog.dismiss();

        // activity跳转器
        resultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            Log.i(TAG, "跳转返回！！！");
            if (jumpDialog.isShowing()) {
                jumpDialog.dismiss();
            }
        });

        settingData = new SettingData(this);
        // 设置默认启动界面
        navView.setSelectedItemId(settingData.getDefaultFragment());

    }

    /**
     * 获取手机安装的所有应用信息
     * @return
     */
    private Map<String, ApplicationInfo> initGoalAppInfoMap() {

        List<PackageInfo> PackageInfoList = getPackageManager().getInstalledPackages(0);

        applicationInfoList = PackageInfoList.stream()
                .filter(packageInfo -> (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0)
                .map(packageInfo -> packageInfo.applicationInfo).collect(Collectors.toList());

        Map<String, ApplicationInfo> goal = applicationInfoList.stream()
                .collect(Collectors.toMap(applicationInfo -> applicationInfo.packageName, applicationInfo -> applicationInfo));

//        Arrays.stream(PackageEnum.values()).forEach(packageEnum -> {
//            try {
//                goal.put(packageEnum.getPackageName(), getPackageManager().getApplicationInfo(packageEnum.getPackageName(), 0));
//            } catch (PackageManager.NameNotFoundException ignored) {
//            }
//        });

        Log.i(TAG, goal.toString());
        return goal;
    }

    /**
     * 获取单个app's info
     * @param packageName
     * @return
     */
    public ApplicationInfo getGoalAppInfoBy(String packageName) {
        return goalAppInfoMap.get(packageName);
    }

    public BottomSheetDialog getBottomSheetDialog(String result) {
        BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(this, R.style.BottomSheetDialogStyle);
        View view = View.inflate(this, R.layout.dialog_bottom_sheet, null);
        TextView scanResult = view.findViewById(R.id.scan_result);
        scanResult.setText(result);

        scanResult.setOnClickListener(v -> {
            ClipData mClipData = ClipData.newPlainText("", result);
            clipboardManager.setPrimaryClip(mClipData);
            Toast.makeText(EasyScanActivity.this, "已复制到剪切板", Toast.LENGTH_SHORT).show();
        });

        BottomSheetBehavior<FrameLayout> behavior = bottomSheetDialog.getBehavior();
        behavior.setDraggable(true);
        behavior.setMaxHeight((int) (getResources().getDisplayMetrics().heightPixels * 0.7));

        bottomSheetDialog.setContentView(view);

        return bottomSheetDialog;
    }


    /**
     * 请求需要的权限（获取相机）
     */
    public void requestPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 1);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.QUERY_ALL_PACKAGES) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.QUERY_ALL_PACKAGES}, 1);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == 1) {
            for (int i = 0; i < permissions.length; i++) {
                if (Manifest.permission.CAMERA.equals(permissions[i]) && grantResults[i] == PackageManager.PERMISSION_DENIED) {
                    Toast.makeText(this, "必须授权摄像头权限才可使用！", Toast.LENGTH_LONG).show();
                    finish();
                    break;
                }
            }
        }
    }
}